<template>
  <el-card>
    <template #header>
      <div class="flex">
        <div class="flex1">学生管理</div>
      </div>
    </template>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="page"
    >
      <el-form-item label="学生姓名" prop="realName">
        <el-input
          v-model="formData.realName"
          placeholder="输入学生姓名（限制10字）"
          maxlength="10"
        />
      </el-form-item>
      <el-form-item label="学生性别" prop="sex">
        <CRadio constKey="sex" v-model="formData.sex" />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="formData.phone" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item
        :label="formData?.cardType == 0 ? '身份证' : '护照'"
        prop="cardNo"
      >
        <el-input v-model="formData.cardNo"></el-input>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker v-model="formData.birthday"></el-date-picker>
      </el-form-item>

      <el-form-item label="国籍" prop="countryName">
        <ApiSelect apiName="country" v-model="formData.countryName" />
      </el-form-item>
      <el-form-item label="所属部落" prop="organizationId">
        <el-input disabled :value="formData.organizationName"></el-input>
      </el-form-item>
      <el-form-item label="是否可用" prop="status">
        <c-radio v-model="formData.status" constKey="status"></c-radio>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">
          提交
        </el-button>
        <el-button @click="$router.back()">取消 </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script lang="ts" setup>
import API from '@/api/api';
import { useMessage } from '@/hooks/useMessage';
import dayjs from '@/utils/dayjs';
import { createRequireRole } from '@/utils/rules';
import { useRequest } from 'vue-hooks-plus';
const route = useRoute();
const message = useMessage(); // 消息弹窗
const isNew = !route.query.id;
useRequest(
  async () => {
    return API.studentController.info({
      userId: route.query.id,
    });
  },
  {
    ready: !!route.query.id,
    onSuccess(res) {
      formData.value = res;
    },
  }
);

const submitReq = useRequest(
  async (sendData: any) => {
    if (isNew) {
      return API.studentController.add(sendData);
    }
    return API.studentController.update({
      id: route.query.id,
      ...sendData,
    });
  },
  {
    manual: true,
  }
);

const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({});
const router = useRouter();
const formRules = reactive({
  cardNo: [createRequireRole()],
  birthday: [createRequireRole()],
  countryName: [createRequireRole()],
  organizationId: [createRequireRole()],
  category: [createRequireRole()],
  phone: [createRequireRole()],
  realName: [createRequireRole()],
  sex: [createRequireRole()],
  status: [createRequireRole()],
});
const formRef = ref(); // 表单 Ref

const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;

  try {
    const data = {
      ...formData.value,
      birthday: dayjs(formData.value.birthday).format('YYYY-MM-DD'),
    };
    await submitReq.runAsync(data);
    if (isNew) {
      message.success('新增成功');
    } else {
      message.success('更新成功');
    }
    router.back();
  } catch (e) {
    formLoading.value = false;
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {};
  formRef.value?.resetFields();
};
</script>
